﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MasterListCreator.Classes;

namespace MasterListCreator.Forms
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        #region Properties
        /// <summary>
        /// Store all Data.
        /// </summary>
        private List<Entities.RecordEntry> Records;
        #endregion

        #region Control Events
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.txtPath.Text = dlg.SelectedPath;
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            this.ExportToExcel();
        }
        #endregion 

        #region Methods
        /// <summary>
        /// Export to Text File.
        /// </summary>
        private void ExportToText()
        {
            string[] path = Classes.Utility.DirectoryListing(this.txtPath.Text.Trim());
            string content = string.Empty;
            foreach (var item in path)
            {
                content += item;
                content += Environment.NewLine;
            }

            Classes.Utility.WriteToTextFile(this.txtPath.Text.Trim() + PublicParam.FILE_NAME, content);
        }

        /// <summary>
        /// Export to Excel File.
        /// </summary>
        private void ExportToExcel()
        {
            try
            {
                string[] path = Classes.Utility.DirectoryListing(this.txtPath.Text.Trim());
                this.GetData();
                Classes.EPPlusHelper.CreateExcelFile(PublicParam.FILE_NAME, path[0],
                    PublicParam.ReadConfig(PublicName.SHEET_NAMES).Split(',')[0], Utility.ToDataTable(this.Records));

                MessageBox.Show(this, "File is exported to " + System.IO.Directory.GetCurrentDirectory() + "\\" + PublicParam.FILE_NAME, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {                
                throw;
            }
        }

        /// <summary>
        /// Init List data.
        /// </summary>
        private void GetData()
        {           
            this.Records = new List<Entities.RecordEntry>();

            Entities.RecordEntry row;
            // Add root path.
            this.Records.Add(new Entities.RecordEntry()
            {
                IsFolder = true,
                FullPath = this.txtPath.Text.Trim(),
                Indent = 0,
                LastModified = Utility.GetLastModified(this.txtPath.Text.Trim())
            });

            ShowAllFoldersUnder(this.txtPath.Text.Trim(), 1);

            // Add File in root Directory
            if (PublicParam.EXPORT_FILE)
            {
                foreach (var file in System.IO.Directory.GetFiles(this.txtPath.Text.Trim()))
                {
                    row = new Entities.RecordEntry()
                    {
                        IsFolder = false,
                        FullPath = System.IO.Path.GetFullPath(file),
                        Indent = 0,
                        Size = Utility.GetSizeReadable(Utility.GetSizeOfPath(System.IO.Path.GetFullPath(file))),
                        LastModified = Utility.GetLastModified(System.IO.Path.GetFullPath(file))
                    };
                    this.Records.Add(row);
                }
            }
        }
                
        /// <summary>
        /// Recursive Directory.
        /// </summary>
        /// <param name="path">Start Path to export.</param>
        /// <param name="indent">Start Indent.</param>
        private void ShowAllFoldersUnder(string path, int indent)
        {
            if (PublicParam.MAX_LEVEL != -1 && indent >= PublicParam.MAX_LEVEL)
            {
                return;
            }

            try
            {
                if ((System.IO.File.GetAttributes(path) & System.IO.FileAttributes.ReparsePoint)
                    != System.IO.FileAttributes.ReparsePoint)
                {
                    Entities.RecordEntry row;
                    foreach (string folder in System.IO.Directory.GetDirectories(path))
                    {
                        if (!PublicParam.EXPORT_EMPTY_DIR && Utility.IsEmpty(folder))
                        {
                            continue;
                        }

                        // Add Sub Directory.
                        row = new Entities.RecordEntry()
                        {
                            IsFolder = true,
                            FullPath =
                            System.IO.Path.GetFullPath(folder),
                            Indent = indent,
                            LastModified = Utility.GetLastModified(System.IO.Path.GetFullPath(folder))
                        };
                        this.Records.Add(row);
                        
                        ShowAllFoldersUnder(folder, indent +  1);

                        // Add File in Sub Directory.
                        if (PublicParam.EXPORT_FILE)
                        {
                            foreach (string file in System.IO.Directory.GetFiles(folder))
                            {
                                row = new Entities.RecordEntry()
                                {
                                    IsFolder = false,
                                    FullPath = System.IO.Path.GetFullPath(file),
                                    Indent = indent + 1,
                                    Size = Utility.GetSizeReadable(Utility.GetSizeOfPath(System.IO.Path.GetFullPath(file))),
                                    LastModified = Utility.GetLastModified(System.IO.Path.GetFullPath(file))
                                };
                                this.Records.Add(row);
                            }
                        }
                    }                   
                }
            }
            catch (UnauthorizedAccessException) { }
        }        
        #endregion
    }
}
